package com.huilian.iotbox.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.dao.CommodityStockRecordDao;
import com.huilian.iotbox.admin.dao.StatsCommodityStockRecordDao;
import com.huilian.iotbox.admin.service.CommodityStockRecordService;
import com.huilian.iotbox.admin.service.StatsCommodityStockRecordService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.CommodityStockRecordDto;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.properties.ConfigProperties;
import com.huilian.iotbox.data.properties.FileProperties;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.vo.CommodityStockRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * @author 龙 路 飞
 * @CreateDate: 2023-08-31 15:21
 * @Description:
 */
@Service
@Slf4j
public class CommodityStockRecordServiceImpl implements CommodityStockRecordService {

    @Autowired
    private FileProperties fileProperties;
    @Resource
    private CommodityStockRecordDao commodityStockRecordDao;
    @Autowired
    private ConfigProperties configProperties;
    @Resource
    private StatsCommodityStockRecordDao statsCommodityStockRecordDao;

    /**
     * 统计使用,根据开始时间和结束时间查询
     *
     * @param startTime
     * @param endTime
     */
    @Override
    public List<CommodityStockRecordVo> findCommodityStockRecordByTime(String startTime, String endTime) {
        List<CommodityStockRecordVo> list = commodityStockRecordDao.findCommodityStockRecordByTime(startTime,endTime);
        return list;
    }

    /**
     * 补货记录查询
     * @Author xuxiaoning
     * @Date 2024/2/19
     *
 * @param commodityStockRecordDto
     * @return com.github.pagehelper.PageInfo
     */
    @Override
    public PageInfo findCommodityStockRecordByMultipleConditions(CommodityStockRecordDto commodityStockRecordDto) {
        PageHelper.startPage(commodityStockRecordDto.getPageNum(), commodityStockRecordDto.getPageSize(), true);
        PageHelper.orderBy("csr.createTime DESC");
        List<CommodityStockRecordVo> list = commodityStockRecordDao.findCommodityStockRecordByMultipleConditions(commodityStockRecordDto);
        PageInfo pagResult = new PageInfo(list);
        if (list.size() < 10) {
            pagResult.setTotal(commodityStockRecordDto.getPageSize() * commodityStockRecordDto.getPageNum());
        } else {
            pagResult.setTotal(commodityStockRecordDto.getPageSize() * commodityStockRecordDto.getPageNum() + 1);
        }
        return pagResult;
    }

    @Override
    public ServerResponse exportList(CommodityStockRecordDto commodityStockRecordDto) {
        List<CommodityStockRecordVo> list = commodityStockRecordDao.findCommodityStockRecordByMultipleConditions(commodityStockRecordDto);
        String[] headers = new String[]{"场地", "设备号", "状态","货道", "商品","库存前", "库存后", "变量", "备注", "售价前", "售价后", "成本价前", "成本价后","时间"};
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区为东八区
        // 格式化日期
        String formattedCreateTime = sdf.format(commodityStockRecordDto.getCreateTime());
        String formattedUpdateTime = sdf.format(commodityStockRecordDto.getUpdateTime());
        String sheetName = "库存记录" + formattedCreateTime + "至" + formattedUpdateTime;
        // 创建了一个excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(10);
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(8, 25 * 256);
//        sheet.createFreezePane(0, 4, 0, 4);
        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font font = wb.createFont();
        //设置字体样式
        //font.setFontHeightInPoints((short) 20);   //--->设置字体大小
        font.setFontName("Courier New");   //---》设置字体，是什么类型例如：宋体
        font.setItalic(true);     //--->设置是否是加粗
        titleStyle.setFont(font);     //--->将字体格式加入到style1中
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直

        //内容样式
        HSSFCellStyle contextStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font contextfont = wb.createFont();
        contextfont.setFontHeightInPoints((short) 13);   //--->设置字体大小
        //设置字体样式
        contextStyle.setFont(contextfont);     //--->将字体格式加入到style1中
        contextStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        contextStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直
        contextStyle.setWrapText(true);//设置自动换行

        //表格第一行
        HSSFRow row1 = sheet.createRow(0);   //--->创建一行
        row1.setHeightInPoints(20);
        HSSFCell cell1 = row1.createCell(0);   //--->创建一个单元格
        // cell1.setCellStyle(titleStyle);
        cell1.setCellValue("库存记录");
        //表格第二行
        HSSFRow r2 = sheet.createRow(1);
        r2.setHeightInPoints(20);
        HSSFCell c2 = r2.createCell(0);
        c2.setCellValue("起始时间：[" + sdf.format(commodityStockRecordDto.getCreateTime()) + "]  " + "  终止时间：[" + sdf.format(commodityStockRecordDto.getUpdateTime()) + "]");

        //标题
        HSSFRow row2 = sheet.createRow(3);           //--->创建一行
        contextStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);// 设置背景色
        contextStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        contextStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        contextStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        contextStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        contextStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        contextfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        contextStyle.setFont(contextfont);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell2 = row2.createCell(i);
            cell2.setCellValue(headers[i]);
            cell2.setCellStyle(contextStyle);
        }
        int index = 0;//记录额外创建的sheet数量
        int j = 0;
        // 循环每行
        for (int i = 4; i < list.size() + 4; i++) {
            if ((i) % 65500 == 0) {
                sheet = wb.createSheet("salesList" + index);
                index++;
            }
            // 创建行
            HSSFRow row = sheet.createRow((i) - (index * 65500));
            // 创建列
            //场地
            HSSFCell contextCell1 = row.createCell(0);
            contextCell1.setCellValue(list.get(j).getStoreName());
            //设备号
            HSSFCell contextCell2 = row.createCell(1);
            contextCell2.setCellValue(list.get(j).getDeviceNo());
            //状态
            HSSFCell contextCell3 = row.createCell(2);
            contextCell3.setCellValue(CommodityStockRecordFirstTypeEnum.getDesc(list.get(j).getFirstType()));
            //货道
            HSSFCell contextCell4 = row.createCell(3);
            if (!StringUtils.isEmpty(list.get(j).getHierarchy()) && !StringUtils.isEmpty(list.get(j).getFreightLane())) {
                contextCell4.setCellValue(list.get(j).getHierarchy()+"层,"+list.get(j).getFirstType()+"货道");
            } else {
                contextCell4.setCellValue("无");
            }
            //商品
            HSSFCell contextCell5 = row.createCell(4);
            contextCell5.setCellValue(list.get(j).getCommodityName());
            //库存前
            HSSFCell contextCell6 = row.createCell(5);
            if (!StringUtils.isEmpty(list.get(j).getStockBefore())) {
                contextCell6.setCellValue(list.get(j).getStockBefore());
            } else {
                contextCell6.setCellValue("无");
            }
            //库存后
            HSSFCell contextCell7 = row.createCell(6);
            if (!StringUtils.isEmpty(list.get(j).getStockAfter())) {
                contextCell7.setCellValue(list.get(j).getStockAfter());
            } else {
                contextCell7.setCellValue("无");
            }
            //变量
            HSSFCell contextCell8 = row.createCell(7);
            if (!StringUtils.isEmpty(list.get(j).getStockBefore()) && !StringUtils.isEmpty(list.get(j).getStockAfter())) {
                contextCell8.setCellValue(list.get(j).getStockBefore() - list.get(j).getStockAfter());
            } else {
                contextCell8.setCellValue("无");
            }
            //备注
            HSSFCell contextCell9 = row.createCell(8);
            if (!StringUtils.isEmpty(list.get(j).getRemark())) {
                contextCell9.setCellValue(list.get(j).getRemark());
            } else {
                contextCell9.setCellValue("无");
            }
            //售价前
            HSSFCell contextCell10 = row.createCell(9);
            if (!StringUtils.isEmpty(list.get(j).getRetailPriceBefore())) {
                contextCell10.setCellValue(list.get(j).getRetailPriceBefore().toString());
            } else {
                contextCell10.setCellValue("无");
            }
            //售价后
            HSSFCell contextCell11 = row.createCell(10);
            if (!StringUtils.isEmpty(list.get(j).getRetailPriceAfter())) {
                contextCell11.setCellValue(list.get(j).getRetailPriceAfter().toString());
            } else {
                contextCell11.setCellValue("无");
            }
            //成价前
            HSSFCell contextCell12 = row.createCell(11);
            if (!StringUtils.isEmpty(list.get(j).getCostPriceBefore())) {
                contextCell12.setCellValue(list.get(j).getCostPriceBefore().toString());
            } else {
                contextCell12.setCellValue("无");
            }
            //成本价后
            HSSFCell contextCell13 = row.createCell(12);
            if (!StringUtils.isEmpty(list.get(j).getCostPriceAfter())) {
                contextCell13.setCellValue(list.get(j).getCostPriceAfter().toString());
            } else {
                contextCell13.setCellValue("无");
            }
            //时间
            HSSFCell contextCell14 = row.createCell(13);
            contextCell14.setCellValue(sdf.format(list.get(j).getCreateTime())
            );
            j++;
            if (j >= list.size()) {
                j = 0;
            }
        }
        // 保存文件
        FileOutputStream fileOut = null;
        String fileName = fileProperties.getSaveImgPath() + "/" + sheetName + ".xls";

        try {
            File f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            // 文件保存的地址和名称
            log.info("------------------------------iot后台库存记录导出:" + fileName);
            fileOut = new FileOutputStream(fileName);
            wb.write(fileOut);

        } catch (IOException e) {
            // 处理文件操作可能发生的IO异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存失败:" + e + fileProperties.getSaveImgPath());
        } catch (Exception e) {
            // 其他异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存过程中发生了错误:" + e);

        } finally {
            // 关闭流
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("fileName", sheetName + ".xls");
        map.put("downloadUrl",configProperties.getAdminBackEndUrl() + "/api/fileExport/download/" +sheetName + ".xls");
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public PageInfo stockStatisticList(CommodityStockRecordDto commodityStockRecordDto) {
        CommodityStockRecordVo commodityStockRecordVo = this.checkTime(commodityStockRecordDto);

        PageHelper.startPage(commodityStockRecordDto.getPageNum(), commodityStockRecordDto.getPageSize(), true);

        //请求数据
        List<CommodityStockRecordVo> list = this.requestStockStatisticData(commodityStockRecordVo,commodityStockRecordDto);

        PageInfo pagResult = new PageInfo(list);
        if (list.size() < 10) {
            pagResult.setTotal(commodityStockRecordDto.getPageSize() * commodityStockRecordDto.getPageNum());
        } else {
            pagResult.setTotal(commodityStockRecordDto.getPageSize() * commodityStockRecordDto.getPageNum() + 1);
        }
        return pagResult;
    }

    private List<CommodityStockRecordVo> requestStockStatisticData(CommodityStockRecordVo commodityStockRecordVo, CommodityStockRecordDto commodityStockRecordDto) {
        //组装参数
        CommodityStockRecordDto stockRecordDto = new CommodityStockRecordDto();
        stockRecordDto.setDateType(commodityStockRecordDto.getDateType());
        stockRecordDto.setUserInfo(commodityStockRecordDto.getUserInfo());
//        stockRecordDto.setFirstType(CommodityStockRecordFirstTypeEnum.OUTBOUND.getCode());
        stockRecordDto.setSecondaryType(commodityStockRecordDto.getSecondaryType());
        stockRecordDto.setUserId(commodityStockRecordDto.getUserId());
        stockRecordDto.setCommodityName(commodityStockRecordDto.getCommodityName());
        stockRecordDto.setDeviceNo(commodityStockRecordDto.getDeviceNo());
        stockRecordDto.setMerchantStoreIdArray(commodityStockRecordDto.getMerchantStoreIdArray());
        stockRecordDto.setAgencyId(commodityStockRecordDto.getAgencyId());
        stockRecordDto.setType(commodityStockRecordDto.getDateType());
        stockRecordDto.setStatus(CommodityStockRecordStatusEnum.COMPLETED.getCode());
        stockRecordDto.setGroupType(commodityStockRecordDto.getGroupType());
        stockRecordDto.setOrderId(commodityStockRecordDto.getOrderId());
        stockRecordDto.setGroupTypeIdArray(commodityStockRecordDto.getGroupTypeIdArray());
        if(commodityStockRecordVo.getEndDateStr().isEqual(commodityStockRecordVo.getLocalDate()) && commodityStockRecordVo.getStartDateStr().isEqual(commodityStockRecordVo.getLocalDate())){
            stockRecordDto.setStartDateStr(DateTimeUtils.getTodayStartTime());
            stockRecordDto.setEndDateStr(DateTimeUtils.getTodayEndTime());
            return commodityStockRecordDao.findTodayStockStatisticList(stockRecordDto);
        }else{
            if(commodityStockRecordDto.getDateType().compareTo(2) == 0){
                stockRecordDto.setStartDateStr(DateTimeUtils.formatByPattern(commodityStockRecordDto.getCreateTime(), "yyyy-MM"));
                stockRecordDto.setEndDateStr(DateTimeUtils.formatByPattern(commodityStockRecordDto.getUpdateTime(), "yyyy-MM"));
            }else{
                stockRecordDto.setStartDateStr(DateTimeUtils.formatByPattern(commodityStockRecordDto.getCreateTime(), "yyyy-MM-dd"));
                stockRecordDto.setEndDateStr(DateTimeUtils.formatByPattern(commodityStockRecordDto.getUpdateTime(), "yyyy-MM-dd"));
            }

            return statsCommodityStockRecordDao.findStatsCommodityStockRecordList(stockRecordDto);
        }
    }

    /**
     * 校验时间
     * */
    private CommodityStockRecordVo checkTime(CommodityStockRecordDto commodityStockRecordDto) {
        // 获取当前的本地时间
        LocalDate localDate = LocalDate.now();
        LocalDate startDateStr = LocalDate.parse(DateTimeUtils.formatByPattern(commodityStockRecordDto.getCreateTime(), "yyyy-MM-dd"));
        log.info("前端参数开始时间：" + startDateStr);
        LocalDate endDateStr = LocalDate.parse(DateTimeUtils.formatByPattern(commodityStockRecordDto.getUpdateTime(), "yyyy-MM-dd"));
        log.info("前端参数结束时间：" + endDateStr);
        if(startDateStr.isAfter(endDateStr)){
            throw new RuntimeException("开始时间不能大于结束时间");
        }
        if(commodityStockRecordDto.getDateType().compareTo(2) == 0 && endDateStr.isAfter(localDate)){
            throw new RuntimeException("时间不能包含本月");
        }
        if(startDateStr.isAfter(localDate) || endDateStr.isAfter(localDate)){
            throw new RuntimeException("开始时间和结束时间不能大于当前时间");
        }
        if(startDateStr.isBefore(localDate) && endDateStr.isEqual(localDate)){
            throw new RuntimeException("统计数据不能包含当天，当天数据请单独查询");
        }
        if(StringUtils.isEmpty(commodityStockRecordDto.getGroupTypeIdArray()) || commodityStockRecordDto.getGroupTypeIdArray().size() == 0){
            throw new RuntimeException("分组不能为空，至少选择一个");
        }
        CommodityStockRecordVo commodityStockRecordVo = new CommodityStockRecordVo();
        commodityStockRecordVo.setStartDateStr(startDateStr);
        commodityStockRecordVo.setEndDateStr(endDateStr);
        commodityStockRecordVo.setLocalDate(localDate);
        return commodityStockRecordVo;
    }

    /**
     * 导出库存统计
     * */
    @Override
    public ServerResponse exportStockStatisticList(CommodityStockRecordDto commodityStockRecordDto) {
        CommodityStockRecordVo commodityStockRecordVo = this.checkTime(commodityStockRecordDto);
        //请求数据
        List<CommodityStockRecordVo> list = this.requestStockStatisticData(commodityStockRecordVo,commodityStockRecordDto);
        if(StringUtils.isEmpty(list) || list.size() == 0){
            return ServerResponse.createByErrorMessage("没有数据可以导出");
        }
        String[] headers = new String[]{"商品ID","运营商","场地名称","设备号", "商品名称", "总数量","总金额", "总成本","总利润"};
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区为东八区
        // 格式化日期
        String formattedCreateTime = sdf.format(commodityStockRecordDto.getCreateTime());
        String formattedUpdateTime = sdf.format(commodityStockRecordDto.getUpdateTime());
        String sheetName = "库存统计" + formattedCreateTime + "至" + formattedUpdateTime;
        // 创建了一个excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(10);
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(8, 25 * 256);
//        sheet.createFreezePane(0, 4, 0, 4);
        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font font = wb.createFont();
        //设置字体样式
        //font.setFontHeightInPoints((short) 20);   //--->设置字体大小
        font.setFontName("Courier New");   //---》设置字体，是什么类型例如：宋体
        font.setItalic(true);     //--->设置是否是加粗
        titleStyle.setFont(font);     //--->将字体格式加入到style1中
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直

        //内容样式
        HSSFCellStyle contextStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font contextfont = wb.createFont();
        contextfont.setFontHeightInPoints((short) 13);   //--->设置字体大小
        //设置字体样式
        contextStyle.setFont(contextfont);     //--->将字体格式加入到style1中
        contextStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        contextStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直
        contextStyle.setWrapText(true);//设置自动换行

        //表格第一行
        HSSFRow row1 = sheet.createRow(0);   //--->创建一行
        row1.setHeightInPoints(20);
        HSSFCell cell1 = row1.createCell(0);   //--->创建一个单元格
        // cell1.setCellStyle(titleStyle);
        cell1.setCellValue("库存统计");
        //表格第二行
        HSSFRow r2 = sheet.createRow(1);
        r2.setHeightInPoints(20);
        HSSFCell c2 = r2.createCell(0);
        c2.setCellValue("起始时间：[" + sdf.format(commodityStockRecordDto.getCreateTime()) + "]  " + "  终止时间：[" + sdf.format(commodityStockRecordDto.getUpdateTime()) + "]");

        //标题
        HSSFRow row2 = sheet.createRow(3);           //--->创建一行
        contextStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);// 设置背景色
        contextStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        contextStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        contextStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        contextStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        contextStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        contextfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        contextStyle.setFont(contextfont);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell2 = row2.createCell(i);
            cell2.setCellValue(headers[i]);
            cell2.setCellStyle(contextStyle);
        }
        int index = 0;//记录额外创建的sheet数量
        int j = 0;
        // 循环每行
        for (int i = 4; i < list.size() + 4; i++) {
            if ((i) % 65500 == 0) {
                sheet = wb.createSheet("salesList" + index);
                index++;
            }
            // 创建行
            HSSFRow row = sheet.createRow((i) - (index * 65500));
            // 创建列
            //商品ID
            HSSFCell contextCell = row.createCell(0);
            if (!StringUtils.isEmpty(list.get(j).getCommodityId())) {
                contextCell.setCellValue(list.get(j).getCommodityId());
            } else {
                contextCell.setCellValue("无");
            }
            HSSFCell contextCell0 = row.createCell(1);
            if (!StringUtils.isEmpty(list.get(j).getName())) {
                contextCell0.setCellValue(list.get(j).getName());
            } else {
                contextCell0.setCellValue("无");
            }
            HSSFCell contextCell1 = row.createCell(2);
            if (!StringUtils.isEmpty(list.get(j).getStoreName())) {
                contextCell1.setCellValue(list.get(j).getStoreName());
            } else {
                contextCell1.setCellValue("无");
            }
            HSSFCell contextCell2 = row.createCell(3);
            if (!StringUtils.isEmpty(list.get(j).getDeviceNo())) {
                contextCell2.setCellValue(list.get(j).getDeviceNo());
            } else {
                contextCell2.setCellValue("无");
            }

            //商品名称
            HSSFCell contextCell3 = row.createCell(4);
            if (!StringUtils.isEmpty(list.get(j).getCommodityName())) {
                contextCell3.setCellValue(list.get(j).getCommodityName());
            } else {
                contextCell3.setCellValue("无");
            }
            //总数量
            HSSFCell contextCell4 = row.createCell(5);
            if (!StringUtils.isEmpty(list.get(j).getTotalQuantity())) {
                contextCell4.setCellValue(list.get(j).getTotalQuantity());
            } else {
                contextCell4.setCellValue("无");
            }
            //总金额
            HSSFCell contextCell5 = row.createCell(6);
            if (!StringUtils.isEmpty(list.get(j).getTotalRetailPrice())) {
                contextCell5.setCellValue(list.get(j).getTotalRetailPrice().toString());
            } else {
                contextCell5.setCellValue("无");
            }

            //总成本
            HSSFCell contextCell6 = row.createCell(7);
            if (!StringUtils.isEmpty(list.get(j).getTotalCostPrice())) {
                contextCell6.setCellValue(list.get(j).getTotalCostPrice().toString());
            } else {
                contextCell6.setCellValue("无");
            }
            //总利润
            HSSFCell contextCell7 = row.createCell(8);
            if (!StringUtils.isEmpty(list.get(j).getTotalProfit())) {
                contextCell7.setCellValue(list.get(j).getTotalProfit().toString());
            } else {
                contextCell7.setCellValue("无");
            }
            j++;
            if (j >= list.size()) {
                j = 0;
            }
        }
        // 保存文件
        FileOutputStream fileOut = null;
        String fileName = fileProperties.getSaveImgPath() + "/" + sheetName + ".xls";
        try {
            File f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            // 文件保存的地址和名称
            log.info("------------------------------iot后台库存记录导出:" + fileName);
            fileOut = new FileOutputStream(fileName);
            wb.write(fileOut);

        } catch (IOException e) {
            // 处理文件操作可能发生的IO异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存失败:" + e + fileProperties.getSaveImgPath());
        } catch (Exception e) {
            // 其他异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存过程中发生了错误:" + e);

        } finally {
            // 关闭流
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("fileName", sheetName + ".xls");
        map.put("downloadUrl",configProperties.getAdminBackEndUrl() + "/api/fileExport/download/" +sheetName + ".xls");
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse stockStatistic(CommodityStockRecordDto commodityStockRecordDto) {
        CommodityStockRecordVo commodityStockRecordVo = this.checkTime(commodityStockRecordDto);
        //请求数据
        List<CommodityStockRecordVo> list = this.requestStockStatisticData(commodityStockRecordVo,commodityStockRecordDto);
        BigDecimal totalProfit = BigDecimal.ZERO;
        BigDecimal totalRetailPrice = BigDecimal.ZERO;
        BigDecimal totalCostPrice = BigDecimal.ZERO;
        int totalQuantity = 0;
        for (CommodityStockRecordVo stockRecordVo : list) {
            totalProfit = totalProfit.add(stockRecordVo.getTotalProfit());
            totalQuantity = totalQuantity + stockRecordVo.getTotalQuantity();
            totalRetailPrice = totalRetailPrice.add(stockRecordVo.getTotalRetailPrice());
            totalCostPrice = totalCostPrice.add(stockRecordVo.getTotalCostPrice());
        }
        CommodityStockRecordVo commodityStockRecordVo1 = new CommodityStockRecordVo();
        commodityStockRecordVo1.setTotalProfit(totalProfit);
        commodityStockRecordVo1.setTotalRetailPrice(totalRetailPrice);
        commodityStockRecordVo1.setTotalCostPrice(totalCostPrice);
        commodityStockRecordVo1.setTotalQuantity(totalQuantity);
        return ServerResponse.createBySuccess(commodityStockRecordVo1);
    }
}
